package cn.tedu.sentinel02.datasource;

import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.datasource.FileRefreshableDataSource;
import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.init.InitFunc;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSON;

import java.net.URL;
import java.util.List;



public class LocalDataSourceInit implements InitFunc {
    //加载json规则  实现初始化
    @Override
    public void init() throws Exception {
        ClassLoader classLoader =
                LocalDataSourceInit.class.getClassLoader();
        URL resource = classLoader.getResource("flowRules.json");
        String file = resource.getFile();

        //线程  解析规则
        ReadableDataSource<String, List<FlowRule>> dataSource =
                new FileRefreshableDataSource<List<FlowRule>>(
                        file, new Converter<String, List<FlowRule>>() {
                    @Override
                    public List<FlowRule> convert(String json) {
                       return JSON.parseArray(json,FlowRule.class);
                    }
                }
                );
//加载规则
        FlowRuleManager.register2Property(dataSource.getProperty());


    }
}
